from selenium.webdriver.support.ui import WebDriverWait
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select

class Base():

    # 初始化驱动
    def __init__(self, driver):
        self.driver = driver

    # 封装打开浏览器的方法
    def open_url(self, url):
        self.driver.get(url)

    # 封装查找页面元素的方法
    def find_element(self, loc):
        # 异常处理
        try:
            WebDriverWait(self.driver,20,0.5).until(lambda driver: driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            # 获取本地时间
            t = time.strftime('%Y%m%d%H%M%S', time.localtime())
            self.driver.save_screenshot(t+'error.png')
            print(e)

    # 封装点击的方法
    def click(self, loc):
        self.find_element(loc).click()

    # 封装输入的方法
    def send_keys(self, loc, text):
        self.find_element(loc).send_keys(text)

    # 封装切换窗口的方法
    def new_window(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])

    # 封装进入iframe框架的方法
    def iframe(self, loc):
       f = self.find_element(loc)
       self.driver.switch_to.frame(f)

    # 封装鼠标单击方法
    def context_click(self, loc):
        ActionChains.context_click(loc).perform()

    # 封装鼠标释放的方法
    def release(self, loc):
        ActionChains.release(loc).perform()

    # 封装键盘回车的方法
    def keys_enter(self, loc):
        self.send_keys(loc, Keys.ENTER)

    # 封装键盘输入空格的方法
    def keys_space(self, loc):
        self.send_keys(loc, Keys.SPACE)

    # 封装滚动的方法
    def scrollTo(self, x):
        self.driver.execute_script(f'window.scrollTo(0,{x})')

    # 封装下拉框的方法
    def select(self, loc, x):
        value = Select(self.find_element(loc))
        value.select_by_value(x)